package com.zcx.common;

import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

public class TaskExecutorConfiguration {

    //四种策略：
    //
    //ThreadPoolExecutor.AbortPolicy:丢弃任务并抛出RejectedExecutionException异常。 默认策略
    //
    //ThreadPoolExecutor.DiscardPolicy：也是丢弃任务，但是不抛出异常。
    //
    //ThreadPoolExecutor.DiscardOldestPolicy：丢弃队列最前面的任务，然后重新尝试执行任务（重复此过程）
    //
    //ThreadPoolExecutor.CallerRunsPolicy：由调用线程处理该任务

    @Bean("taskExecutor")
    public Executor schedulingTaskExecutor() {
        return initExecutor(10, 10, 1, new ThreadPoolExecutor.AbortPolicy(), "异步taskExecutor-");
    }


    private Executor initExecutor(int corePoolSize, int maxPoolSize, int queueCapacity, RejectedExecutionHandler rejectedExecutionHandler, String threadNamePrefix) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数
        executor.setCorePoolSize(corePoolSize);
        // 最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        // 队列容量
        executor.setQueueCapacity(queueCapacity);
        // 丢弃任务并抛出RejectedExecutionException异常。 默认策略
        executor.setRejectedExecutionHandler(rejectedExecutionHandler);
        // 线程名称前缀
        executor.setThreadNamePrefix(threadNamePrefix);
        //活跃时间
        executor.setKeepAliveSeconds(60);
        // 线程池关闭前最大等待时间，确保最后一定关闭
        executor.setAwaitTerminationSeconds(60);
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //executor.setTaskDecorator(new ContextCopyingDecorator);
        //初始化线程
        executor.initialize();
        return executor;
    }
}
